<template>
  <div class="tabs"
       :class="{'active':isFixed,'border-b':isBorderB}">
    <ul class="tab">
      <li class="tab-item"
          v-for="(item,key) in tabs"
          :class="{active:curTab == key}"
          :key="`tabs${key}`"
          @click="toggle(item,key)">
        <span :ref="'tab'+key">{{item}}</span>
      </li>
    </ul>
    <div class="tab-bar">
      <span class="bar"
            :style="tabBarStyle"></span>
    </div>
  </div>
</template>

<script>

export default {
  name: 'CTabs',
  props: {
    tabs: {
      // {key:value}...
      type: Object,
      required: true
    },
    value: {
      type: [Number, String],
      required: false
    },
    isLoading: Boolean,
    isBorderB: {
      type: Boolean,
      default: true
    },
    isFixed: Boolean
  },
  data () {
    return {
      curTab: '',
      width: 0,
      tabBarStyle: {
        width: 0,
        transform: 'translate(0,0)'
      },
      addW: 0
    }
  },
  watch: {
    value: {
      handler (val) {
        this.curTab = val
      },
      immediate: true
    },
    curTab (nVal, oVal) {
      this.$emit('input', nVal)
      if (nVal === oVal) {
        return
      }
      this.handleWidth()
    },
    tabs: {
      handler (val) {
        if (!Object.keys(val).length) return
        this.$nextTick(() => {
          this.handleWidth()
        })
      },
      immediate: true
    }
  },
  methods: {
    toggle (item, key) {
      if (this.isLoading || this.curTab == key) return // eslint-disable-line
      this.curTab = key
      this.$emit('toggle', this.curTab)
    },
    handleWidth () {
      if (!this.$refs['tab' + this.curTab][0]) {
        let timer = setTimeout(() => {
          this.handleWidth()
          clearTimeout(timer)
          timer = null
        }, 20)
        return
      }
      let tabWidth = this.$refs['tab' + this.curTab][0].offsetWidth
      // let width = 32 * window.devicePixelRatio
      let width = tabWidth
      let tabLeft = this.$refs['tab' + this.curTab][0].offsetLeft
      this.tabBarStyle.width = width + 'px'
      this.tabBarStyle.transform = 'translate(' + (tabLeft + (tabWidth - width) / 2) + 'px,0)'
    }
  }
}
</script>

<style lang="stylus" scoped>
.tabs
  position relative
  .tab
    flexAlign(center)
    height 45px
  .tab-item
    overflow hidden
    flex 1
    margin-right 17px
    text-align center
    span
      color $color-font-l
      font-size 16px
      // transition all 0.2s
  .tab-item.active
    span
      position relative
      border-radius 2px
      color $color-main
      font-weight 600
  .tab-bar
    position absolute
    right 0
    bottom 0
    left 0
    .bar
      position absolute
      bottom 0
      height 3px
      background-color $color-main
      transition transform 0.25s
      transform translate(0, 0)
</style>
